﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using Aquarinum.Base.Infrastructure.Ioc;
using Aquarinum.Util.Interface.Log;
using Aquarinum.WebSocekt.Core.Utils;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using NLog;

namespace Aquarinum.WebSocket.Server
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");
            try
            {
                BuildWebHost(args).Run();
            }
            catch (Exception e)
            {
                var ex = e;
                while (ex != null)
                {
                    Console.WriteLine(ex);
                    Console.WriteLine("===================================");
                    Console.WriteLine(Environment.NewLine);
                    Console.WriteLine("===================================");
                    ex = e.InnerException;
                }


             
            }
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            var host = "0.0.0.0:18427";
            if (args != null && args.Any())
                try
                {
                    var config = JsonConvert.DeserializeObject<WebSocketServerConfig>(args[0].DecodeBase64());
                    WebSocketServerConfig.Default = config;
                    host = config.Host;
                }
                catch (Exception e)
                {
                    var argsstring = (args ?? new List<string>().ToArray()).Aggregate(string.Empty,
                        (current, arg) => current + arg + Environment.NewLine);

                    Console.WriteLine($"解析启动参数出错{argsstring}");
                }

            return WebHost.CreateDefaultBuilder().UseKestrel()
                .UseIISIntegration().UseUrls($"http://{host}")
                .UseStartup<Startup>()
                .Build();
        }
    }
}